package com.jiang.books.service.jpa;

import java.math.BigInteger;
import java.util.List;

import javax.annotation.Resource;

//import javax.persistence.EntityManager;
//import javax.persistence.PersistenceContext;

import org.apache.log4j.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jiang.books.domain.User;
import com.jiang.books.domain.UserBook;
import com.jiang.books.repository.AwardRepository;
import com.jiang.books.repository.UserBookRepository;
import com.jiang.books.service.IUserService;
import com.jiang.books.service.UserBookService;

@Service("jpaUserBookService")
@Repository
@Transactional
public class UserBookServiceImpl implements UserBookService {

	private static final Logger log = Logger.getRootLogger();
	
	//@PersistenceContext
	//private EntityManager entityManager;
	
	@Autowired
	private UserBookRepository repository;
	
	@Resource(name="jpaUserService")
	private IUserService userSer;

	@Override
	public List<UserBook> findByUser(User user) {
		log.info("UserBookService#Find UserBook by user: " + user);
		return repository.findByUser(user);
	}
	
	@Override
	public List<UserBook> findByUserId(BigInteger userId) {
		log.info("UserBookService#Find UserBook by user id: " + userId);
		
		User user = userSer.findById(userId);
		log.info("UserBookService#User: " + user);
		
        return repository.findByUser(user);
	}

	@Override
	public UserBook findById(BigInteger id) {
		log.info("Award#Find Award by id: " + id);
        return repository.findOne(id);
	}

	@Override
	public UserBook save(UserBook book) {
		log.info("Book#Save Book with id: " + (!book.isNew() ? book.getId() : "not yet generated"));
		return repository.save(book);
	}

	@Override
	public void delete(UserBook book) {
        repository.delete(book);
        log.info("Award#Award with id: " + book.getId() + " deleted successfully");
	}
	
}